<?php

namespace App\Admin\Forms\Setting;

use Encore\Admin\Widgets\Form;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use App\Models\About as Model;

class About extends Form
{
    /**
     * The form title.
     *
     * @var string
     */
    public $title = '关于我们';

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return RedirectResponse
     */
    public function handle(Request $request)
    {
        $data = $request->all([
            'phone',
            'email',
            'service_agreement',
        ]);

        foreach ($data as $field => $value) {
            Model::set(Model::TYPE_ABOUT, $field, $value);
        }

        admin_success('保存成功.');

        return back();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->text('phone', '客服电话')->rules('required');
        $this->email('email', '客服邮箱')->rules('email|required');
        $this->text('service_agreement', '服务协议')->rules('required');
    }

    /**
     * The data of the form.
     *
     * @return array $data
     */
    public function data()
    {
        $data = Model::whereType(Model::TYPE_ABOUT)
            ->pluck('meta_value', 'meta_key')->toArray();

        return [
            'phone' => $data['phone'] ?? "13212341234",
            'email' => $data['email'] ?? "example@email.com",
            'service_agreement' => $data['service_agreement'] ?? "https://example.com/agreement.html",
        ];
    }
}
